package com.doubao.auth.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.doubao.auth.config.JwtConfig;
import com.doubao.auth.dto.JwtAuthResponse;
import com.doubao.auth.dto.PhoneLoginRequest;
import com.doubao.auth.entity.AuthUser;
import com.doubao.auth.mapper.AuthUserMapper;
import com.doubao.auth.util.JwtUtils;
import com.doubao.common.result.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
@Slf4j
public class PhoneAuthService {

    private final JwtUtils jwtUtils;
    private final AuthUserMapper authUserMapper;
    private final RedisTemplate<String, String> redisTemplate;
    private final JwtConfig jwtConfig;
    private final VerificationCodeService verificationCodeService;
    private final PasswordEncoder passwordEncoder;

    private static final String REFRESH_TOKEN_KEY_PREFIX = "refresh:token:";

    /**
     * 手机号验证码登录
     */
    @Transactional
    public Result<JwtAuthResponse> loginByPhone(PhoneLoginRequest request) {
        try {
            // 验证码校验
            boolean isValid = verificationCodeService.verifyCode(request.getPhoneNumber(), request.getCode());
            if (!isValid) {
                return Result.failed("验证码错误或已过期");
            }

            // 查询用户
            LambdaQueryWrapper<AuthUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AuthUser::getPhone, request.getPhoneNumber());
            AuthUser user = authUserMapper.selectOne(queryWrapper);

            // 如果用户不存在，则自动注册
            if (user == null) {
                user = registerNewUser(request.getPhoneNumber());
            }

            // 生成令牌
            String token = jwtUtils.generateToken(user.getUsername());
            String refreshToken = jwtUtils.generateRefreshToken(user.getUsername());

            // 将刷新令牌存入Redis，设置7天过期
            redisTemplate.opsForValue().set(
                    REFRESH_TOKEN_KEY_PREFIX + user.getUsername(),
                    refreshToken,
                    jwtConfig.getRefreshExpiration(),
                    TimeUnit.DAYS
            );

            // 更新用户最后登录信息
            user.setLastLoginTime(LocalDateTime.now());
            user.setLastLoginIp(request.getIp());
            user.setLoginCount(user.getLoginCount() + 1);
            authUserMapper.updateById(user);

            // 构建响应对象
            JwtAuthResponse authResponse = new JwtAuthResponse();
            authResponse.setToken(token);
            authResponse.setRefreshToken(refreshToken);
            authResponse.setUserId(user.getId());
            authResponse.setUsername(user.getUsername());
            authResponse.setNickname(user.getNickname());
            authResponse.setAvatar(user.getAvatar());
            authResponse.setVipStatus(user.getVipStatus());

            return Result.success(authResponse);
        } catch (Exception e) {
            log.error("手机号登录失败", e);
            return Result.failed("登录失败: " + e.getMessage());
        }
    }

    /**
     * 注册新用户
     * @param phoneNumber 手机号
     * @return 新用户信息
     */
    private AuthUser registerNewUser(String phoneNumber) {
        AuthUser user = new AuthUser();
        user.setUuid(UUID.randomUUID().toString().replace("-", ""));

        // 使用手机号后4位作为用户名前缀
        String userNamePrefix = "user_" + phoneNumber.substring(phoneNumber.length() - 4);

        // 确保用户名唯一
        String username = userNamePrefix;
        int suffix = 1;
        while (checkUsernameExists(username)) {
            username = userNamePrefix + "_" + suffix++;
        }

        user.setUsername(username);

        // 随机密码
        String randomPassword = UUID.randomUUID().toString().substring(0, 16);
        user.setPassword(passwordEncoder.encode(randomPassword));

        user.setNickname(username);
        user.setPhone(phoneNumber);
        user.setStatus(1); // 正常状态
        user.setDeleted(0); // 未删除
        user.setVipStatus(0); // 非VIP
        user.setLoginCount(1); // 首次登录
        user.setDailyTokensLimit(10000); // 默认每日token限制
        user.setTotalTokensUsed(0L); // 初始token使用量
        user.setRegisterSource("phone"); // 注册来源
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());

        authUserMapper.insert(user);
        return user;
    }

    /**
     * 检查用户名是否存在
     * @param username 用户名
     * @return 是否存在
     */
    private boolean checkUsernameExists(String username) {
        LambdaQueryWrapper<AuthUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AuthUser::getUsername, username);
        return authUserMapper.selectCount(queryWrapper) > 0;
    }
}